/*
 *   Copyright 1999-2016 Asiainfo Technologies(China),Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 */

package com.asiainfo.redis.web;

import com.asiainfo.redis.entity.OperLog;
import com.asiainfo.redis.entity.Result;
import com.asiainfo.redis.service.OperLogService;
import com.asiainfo.redis.utils.SpringContextUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @version v 1.0 on 2016/4/29 10:09
 * @auther william.xu
 */
public class CheckLoginlInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws
            Exception {
        String xRequestWith = request.getHeader("X-Requested-With");
        if (xRequestWith != null && "XMLHttpRequest".equalsIgnoreCase(xRequestWith)) {
            Object principal = SecurityUtils.getSubject().getPrincipal();
            if (principal == null) {
                Result result = new Result<>();
                result.setSuccess(false);
                result.setErrorMsg("没有登录或会话过期，请重新登录！");
                ObjectMapper mapper = new ObjectMapper();
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(mapper.writeValueAsString(result));
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView
            modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception
            ex) throws Exception {
        //但如果按前面的baseController配合@ExceptionHandler做了处理，这里的ex就变成了null
//        if(handler instanceof HandlerMethod){
//            HandlerMethod method = (HandlerMethod)handler;
//            System.out.println(method.getMethod());
//            MethodParameter[] methodParameters = method.getMethodParameters();
//            for(MethodParameter methodParameter : methodParameters){
//                System.out.println(methodParameter.getParameterName());
//            }
//        }
        String xRequestWith = request.getHeader("X-Requested-With");
        if (xRequestWith != null && "XMLHttpRequest".equalsIgnoreCase(xRequestWith)) {
            Object principal = SecurityUtils.getSubject().getPrincipal();
            if (principal != null) {
                OperLog operLog = new OperLog();
                operLog.setLoginName(principal.toString());

                Map<String, String[]> parameterMap = request.getParameterMap();
                ObjectMapper mapper = new ObjectMapper();
                String requestParams = mapper.writeValueAsString(parameterMap);
                operLog.setRequestParams(requestParams);

                operLog.setClientIp(request.getRemoteAddr());
                operLog.setOperUrl(request.getRequestURI());
                OperLogService operLogService = SpringContextUtil.getBean(OperLogService.class);
                operLogService.saveOperLog(operLog);
            }
        }

    }
}
